package com.shiguiwu.springboot3.search.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import jakarta.validation.constraints.NotNull;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @description: 测试Sentinel
 * @author: stone
 * @date: Created by 2023/12/15 20:40
 * @version: 1.0.0
 * @pakeage: com.shiguiwu.springboot3.search.controller
 */
@RestController
public class SentinelController {



    static {
        List<FlowRule> rules = new ArrayList<>();

        //创建一个流控规则
        FlowRule rule = new FlowRule();
        //对/sayHello这个资源限流
        rule.setResource("/sayHello");
        //基于qps限流
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        //qps最大为2，超过2就要被限流
        rule.setCount(2);

        rules.add(rule);

        //设置规则
        FlowRuleManager.loadRules(rules);
    }

    @GetMapping("/sayHello")
    public String sayHello() throws InterruptedException {
        return "hello";
    }


    // value：资源名称 blockHandler：设置限流或降级处理的类
    @SentinelResource(value = "/ann", blockHandler = "exceptionHandler")
    @ResponseBody
    @RequestMapping(path = "/ann", method = RequestMethod.GET)
    public String ann() {
        // 使用限流规则
        return "Hello Sentinel";
    }

    public String exceptionHandler(@NotNull BlockException e) {
        e.printStackTrace();
        return "系统繁忙，请稍后再试";
    }


}
